import React,{useState,useEffect} from 'react'
import marked, { options } from 'marked'
import '../static/css/AddArticle.css'
import 'antd/dist/antd.css';
import {withRouter} from 'react-router-dom'
import {Row,Col,Input,Select,Button,DatePicker, message,Popconfirm ,Upload} from 'antd'
import axios from 'axios'
import servicePage from '../config/apiUrl'
import reactDom from 'react-dom';
import moment from 'moment'
import {
    UploadOutlined,
  } from '@ant-design/icons';




const {Option} =  Select//解析选择
const {TextArea} = Input
const today = moment(); // 当天日期
function AddArticle(props){
    const [articleId, setArticleId] = useState(0)  // 文章的ID，如果是0说明是新增加，如果不是0，说明是修改
    const [articleTitle, setArticleTitle] = useState('')   //文章标题
    const [articleContent, setArticleContent] = useState('')  //markdown的编辑内容
    const [markdownContent, setMarkdownContent] = useState('预览内容') //html内容
    const [introducemd, setIntroducemd] = useState()            //简介的markdown内容
    const [introducehtml, setIntroducehtml] = useState('等待编辑...') //简介的html内容
    const [showDate, setShowDate] = useState()   //发布日期
    const [updateDate, setUpdateDate] = useState(moment().format('YMMDD')) //修改日志的日期
    const [typeInfo, setTypeInfo] = useState([]) // 文章类别信息
    const [selectedType, setSelectType] = useState('请选择类型') //选择的文章类别
    const [selectedTypeId, setSelectTypeId] = useState(0) //选择的文章类别


    useEffect(() => {
        getTypeInfo()
        //在修改的时候获取文章Id
        let tmpId = props.match.params.id
        if(tmpId){
            setArticleId(tmpId)
            getArticleById(tmpId)
        }
    }, [])


    const renderer = new marked.Renderer()
    marked.setOptions({
        renderer:renderer,
        gfm:true,
        pedantic:false,
        sanitize:false,
        tables:true,
        breaks:false,
        smartLists:true,
        smartypants:false
      })
    //修改文章信息实时跟新预览
    const changeContent = (e)=>{
        setArticleContent(e.target.value)
        let html = marked(e.target.value)
        setMarkdownContent(html)
    }
    const changeIntruduce=(e)=>{
        setIntroducemd(e.target.value)
        let html = marked(e.target.value)
        setIntroducehtml(html)
    }
    //从数据借口获得文章类别的信息
    const getTypeInfo = ()=>{
        axios({
            method:'get',
            url:servicePage.getTypeInfo,
            withCredentials:true
        }).then((res)=>{
            if(res.data.data=='没有登陆'){
                localStorage.removeItem('openId')
                props.history.push('/')
            }else{
                setTypeInfo(res.data.data)
            }
        })
    }
    const selectTypeHandle = (value)=>{
        setSelectTypeId(value)
        setSelectType(value)
    }
    //保存文章文章时进行判定，有没有一些东西为空
    const saveArticle=()=>{
        
        if(selectedType==='请选择类型'){
            message.error("必须选择文章类型")
            return false
        }else if(!articleTitle){
            message.error("文章标题不能为空")
            return false
        }else if(!showDate){
            message.error("发布日期不能为空")
            return false
        }else if(!introducemd){
            message.error("文章介绍不能为空")
            return false
        }else if(!articleContent){
            message.error("文章内容不能为空")
            return false
        }
        // message.success('')
        let dataProps={}
        dataProps.type_id = selectedTypeId
        dataProps.title = articleTitle
        dataProps.content = articleContent
        dataProps.introduce = introducemd
        let dataText = showDate.replace(/-/g,'')
        dataProps.addTime = dataText
        if(articleId===0){
            dataProps.view_count = 0;
            axios({
                method:'post',
                url:servicePage.addArticle,
                data:dataProps,
                withCredentials:true
            }).then(
                res=>{
                    //
                    setArticleId(res.data.insertId) 
                    if(res.data.isSuccess){
                        message.success("添加文章成功")
                    }else{
                        message.error('添加文章失败')
                    }
                }
                )
        }else{
            dataProps.id = articleId
            axios({
                method:'post',
                url:servicePage.updateArticle,
                data:dataProps,
                withCredentials:true
                }).then(
                    res=>{
                        if(res.data.isSuccess){
                            message.success("修改成功")
                        }else{
                            message.error("修改失败")
                        }
                    }
                )
        }
    }

    const getArticleById = (id)=>{
        axios(servicePage.getArticleById+id,{
            withCredentials:true
        }).then(
            res=>{
                let articleInfo = res.data.data[0]
                setArticleTitle(articleInfo.title)
                setSelectType(articleInfo.typeName)
                setSelectTypeId(articleInfo.type_id)
                setArticleContent(articleInfo.content)
                let html = marked(articleInfo.content)
                setMarkdownContent(html)
                setIntroducemd(articleInfo.introduce)
                let tmpIntroduce = marked(articleInfo.introduce)
                setIntroducehtml(tmpIntroduce)
                //点击修改之后，获取上一次修改的时间
                setShowDate(moment(articleInfo.addTime,'YYYYMMDD').format("YYYY-MM-DD"))
            }
        )
    }

    //上传文件并且解析的实现
    const uploadProps = {
        beforeUpload(file){
            setArticleTitle(file.name.replace(/\.md/,''))
            setShowDate(moment().format('YMMDD'))
            let read = new FileReader()
            read.readAsText(file,'utf8')
            read.onload=function(f){  
                setArticleContent(this.result)
            }
            return false
        }
      };

    return (
        <div>
            <Row gutter={5}>
                <Col span={18}>
                    <Row gutter={[10,10]}>
                        <Col span={18}>
                            <Input 
                            value = {articleTitle}
                            onChange={e=>{setArticleTitle(e.target.value)}}
                            placeholder='博客标题' 
                            size='large'>
                            </Input>
                        </Col>
                        <Col span={6}>
                            <Select value={selectedType} size="large" onChange={selectTypeHandle}>
                                {
                                    typeInfo.map((item,index)=>{
                                        return (<Option key={index} value={item.id}>{item.typeName}</Option>)
                                    })
                                }
                            </Select>
                        </Col>
                        <Col span={12}>
                            <TextArea className='markdown-content'
                            rows={35}
                            placeholder='文章内容'
                            value={articleContent}
                            onChange={changeContent}
                            >
                            </TextArea>
                        </Col>
                        <Col span={12}>
                            <div className='show-html'
                            dangerouslySetInnerHTML={{__html: markdownContent}}
                            >
                            </div>
                        </Col>
                    </Row>
                </Col>
                <Col span={6}>
                    <Row gutter={[10,10]}>
                        <Col span={9}>
                            <Upload {...uploadProps}>
                                <Button size='large' icon={<UploadOutlined />}>Upload</Button>
                            </Upload>
                        </Col>
                        <Col span={11} offset={4}>
                            <Button size='large' type='primary' onClick={saveArticle}>发布文章</Button>
                        </Col>
                        <Col span={24}>
                            <TextArea
                            rows={6}
                            placeholder='文章简介'
                            value={introducemd}
                            onChange={changeIntruduce}
                             ></TextArea>
                        </Col>
                        <Col span={24}>
                            <div className='introduce-html'
                            dangerouslySetInnerHTML={{__html: introducehtml}}
                            >
                            </div>
                        </Col>
                        <Col span={24}>
                            <div className = 'lastChangeTime'>
                                上次修改时间：{showDate}
                            </div>
                            <div className='date-select'>
                                请选择日期：
                                <DatePicker
                                onChange={(date,dateString)=>setShowDate(dateString)}
                                placeholder='发布日期'
                                size='large'
                                defaultValue={moment(today)}
                                ></DatePicker>
                            </div>
                        </Col>
                    </Row>
                </Col>

            </Row>
        </div>
    )
}
export default AddArticle
